package com.link.base.tencent.ocr.service;

import com.link.base.tencent.ocr.model.OcrImg;
import com.link.base.tencent.ocr.util.OcrUtil;
import com.link.base.tencent.secret.util.SecretUtil;
import com.link.base.tencent.youtu.model.PublicAppInfo;
import com.link.core.basic.model.UploadImgInfo;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.ImageUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;

/**
 * ocr服务
 * 
 * @author ouyangzhenqiang
 * @date 2018/12/29
 */
@Service
public class OcrServiceImpl implements OcrService {
    /**
     * 判断
     */
    private static final String Y_FLAG = "Y";
    private static final String N_FLAG = "N";
    
    @Override
    public String businessCard(OcrImg record) throws Exception {
        String imgUrl = this.getImgUrl(record, "ocr-business-card");
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(UserUtil.getUser().getCorpid().toString());
        return OcrUtil.businessCard(publicAppInfo.getSecret(), publicAppInfo.getAppId(), publicAppInfo.getBucket(), imgUrl);
    }
    
    @Override
    public String idCard(OcrImg record) throws Exception {
        String imgUrl = this.getImgUrl(record, "ocr-id-card");
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(UserUtil.getUser().getCorpid().toString());
        return OcrUtil.idCard(publicAppInfo.getSecret(), publicAppInfo.getAppId(), publicAppInfo.getBucket(), imgUrl);
    }

    @Override
    public String getImgUrl(OcrImg record, String imgType) throws Exception {
        if (StringUtils.isBlank(imgType)) {
            throw new ServiceException("OCR-001");
        }
        String imgHttpUrl;
        String isCode = record.getIsCode();
        if (Y_FLAG.equals(isCode)) {
            // 图片base64编码
            String strImg = record.getImgStr();
            if (StringUtils.isBlank(strImg)) {
                throw new ServiceException("OCR-002");
            }
            // 存储图片至服务器，获取图片HTTP链接
            UploadImgInfo uploadImgInfo = ImageUtil.UploadImage(strImg, imgType);
            imgHttpUrl = uploadImgInfo.getFileHttpPath();
        } else if (N_FLAG.equals(isCode)) {
            // 前端直接提供的图片URL
            String url = record.getUrl();
            if (StringUtils.isBlank(url)) {
                throw new ServiceException("OCR-003");
            }
            imgHttpUrl = url;
        } else {
            throw new ServiceException("OCR-004");
        }
        return imgHttpUrl;
    }
}
